﻿using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Swashbuckle.AspNetCore.Swagger;
using System.Collections.Generic;

namespace dreamwork.apigateway.api
{
	public class Startup
	{
		public Startup(IConfiguration configuration)
		{
			Configuration = configuration;
		}

		public IConfiguration Configuration { get; }

		// This method gets called by the runtime. Use this method to add services to the container.
		public void ConfigureServices(IServiceCollection services)
		{
			services.AddOcelot(Configuration);
			services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
			 .AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme,
				 jwtoptions =>
				 {
					 TokenValidationParameters validateParameter = new TokenValidationParameters
					 {
						 ValidateIssuer = false,
						 ValidateAudience = false
					 };
					 jwtoptions.TokenValidationParameters = validateParameter;
					 jwtoptions.RequireHttpsMetadata = false;
					 jwtoptions.Authority = Configuration["IdentityUrl"];
				 },
				 referenceoptions =>
				 {

				 });
			services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
			services.AddHttpContextAccessor();
			services.AddSwaggerGen(options =>
			{
				options.SwaggerDoc("ApiGateway", new Info { Title = "API GATEWAY", Version = "v1" });

			});
		}

		// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
		public void Configure(IApplicationBuilder app, IHostingEnvironment env)
		{
			if (env.IsDevelopment())
			{
				app.UseDeveloperExceptionPage();
			}
			else
			{
				app.UseHsts();
			}

			app.UseHttpsRedirection();
			app.UseMvcWithDefaultRoute();

			var apis = new Dictionary<string, string>
			{
				{ "dreamworkauth", "Auth API" },
				{ "dreamworkwebapi", "Web API" },
				{ "dreamworkexamapi", "Exam API" },
				{ "dreamworkmembercenterapi", "Member Center API" },
				{ "dreamworkpayapi", "Pay API" },
			};

			app.UseSwagger()
		   .UseSwaggerUI(options =>
		   {
			   foreach (var api in apis)
			   {
				   options.SwaggerEndpoint($"/{api.Key}/swagger.json", api.Value);
			   }
		   });
			app.UseStaticFiles();
			app.UseOcelot().Wait();
		}
	}
}
